package com.fanshuai.soring.boot.mvc.metrics;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class MetricsHandlerMapping extends SimpleUrlHandlerMapping {
    MetricsOutput metricsOutput;

    public MetricsHandlerMapping(MetricsOutput output) {
        super();

        this.metricsOutput = output;
        Map<String, Object> handlerMap = new HashMap<>();
        handlerMap.put("/", output);
        super.setUrlMap(handlerMap);
    }

    @Override
    protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
        String path = request.getRequestURI();
        if (path.startsWith("/metrics")) {
            return metricsOutput;
        }
        String headers = request.getHeader("metrics");
        if (StringUtils.isNotBlank(headers)) {
            return metricsOutput;
        }

        return super.getHandlerInternal(request);
    }
}
